<?php

namespace App\Http\Controllers\applet_api;

use App\Http\Controllers\Controller;
use App\Models\AppCartItem;
use App\Models\AppProduct;
use App\Models\AppProductSku;
use App\Models\AppProductType;
use App\Models\TrainBrochure;
use Illuminate\Http\Request;

class ProductController extends Controller
{

    public function index(Request $Request)
    {
        $search = $Request->search;
        $type = $Request->type ?: 0;
        $limit = $Request->limit ?: 30;
        $page = $Request->page ?: 1;
        $page = $page * $limit - $limit;
        $sql = AppProduct::when($search, function ($query, $search) {
                    return $query->where('title','like', '%'.$search.'%');
                })
                ->when($type, function ($query, $type) {
                    return $query->where('type', $type);
                });
        $total = $sql->count();
        $data = $sql->skip($page)->take($limit)->orderBy('sort','asc')->get();
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data,'total'=>$total]);
    }

    public function types(Request $Request)
    {
        $data = AppProductType::orderBy('id','desc')->get();
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data]);
    }

    public function info(Request $Request)
    {
        $data = AppProduct::with('skus')->where('id',$Request->id)->first();
        $data->increment('clicks');
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data]);
    }

    public function form(Request $Request)
    {
        $arr = [];
        $arr['name'] = $Request->name;
        $arr['org'] = $Request->org;
        $arr['project'] = $Request->project;
        $arr['address'] = $Request->address;
        $arr['nums'] = $Request->nums;
        $data = new TrainBrochure();
        $data->create_time = time();
        $data->mobile = $Request->mobile;
        $data->user_id = $Request->uid;
        $data->update_time = time();
        
        if(!$Request->is_cart){
            $cart_item = [['user_id'=>$Request->uid,'product_sku_id'=>$Request->sku_id,'amount'=>1]];
            $arr['cart_item'] = $cart_item;
        }else{
            $cart_item = AppCartItem::where('user_id',$Request->uid)->where('type',0)->get();
            //清空购物车
            $arr['cart_item'] = $cart_item;
        }
        $data->content = json_encode($arr);
        $data->type = 1;
        $data->save();
        if($data->id){
            return response()->json(['code' => '200', 'msg' => '操作成功']);
        }
        return response()->json(['code' => '403', 'msg' => '操作失败']);
    }

}
